const db = require('./db')

const findOne = function(table, where, callback) { //查找一条；
  let _WHERE = ''

  for (let k in where) {
    _WHERE += k + '=\'' + where[k] + '\' AND '
  }

  _WHERE = _WHERE.slice(0, -4)

  const sql = 'SELECT * FROM ' + table + ' where ' + _WHERE + ' LIMIT 1'
 db.query(sql, [], function(data) {
    callback(data[0])
  })
}
const select = function(table, where, callback, or = null,desc = null) { //查找所有；

  let _WHERE = ''

  for (let k in where) {
    _WHERE += k + (where[k] == null ? ' is null ' : '=\'' + where[k] + '\'') + ' AND '
  }

  _WHERE = _WHERE.slice(0, -4)

  if (where && or) {
    _WHERE = '(' + _WHERE;
    _WHERE += ') or ('
    let flag = false;
    for (let k2 in or) {
      flag = true
      _WHERE += k2 + (or[k2] == null ? ' is null ' : '=\'' + or[k2] + '\'') + ' and '
    }

    _WHERE = _WHERE.slice(0, -4)
    _WHERE += ')'
    if (!flag) {
      _WHERE = _WHERE.slice(0, -2)
    }
  }

  let descData = '';

  if (desc) {
    descData = ' order by ' +desc +  ' desc '
  }

  const sql = 'SELECT * FROM ' + table + (_WHERE ? ' where ' : '') + _WHERE + descData
 db.query(sql, [], callback)
}

const insert = function(table, obj, callback) {

  let fields = ''
  let values = ''
  for (let k in obj) {
    fields += k + ','
    values = values + '\'' + `${obj[k]}` + '\','
  }
  fields = fields.slice(0, -1)
  values = values.slice(0, -1)
  const sql = 'INSERT INTO ' + table + '(' + fields + ') VALUES(' + values + ')'

 db.query(sql, [], callback)
}

const update = function(table, sets, where, callback) {
  let _SETS = ''
  let _WHERE = ''

  for (let k in sets) {
    if (sets[k] == null) continue;
    _SETS += k + '=\'' + `${sets[k]}` + '\','
  }

  _SETS = _SETS.slice(0, -1)

  for (let k2 in where) {
    _WHERE += k2 + '=\'' + where[k2] + '\' AND '
  }
  _WHERE = _WHERE.slice(0, -4)
  const sql = 'UPDATE ' + table + ' SET ' + _SETS + ' where ' + _WHERE

 db.query(sql, [], callback)
}

const del = function(table, where, callback) {
  let _WHERE = ''
  for (let k2 in where) {
    _WHERE += k2 + '=\'' + where[k2] + '\' AND '
  }
  _WHERE = _WHERE.slice(0, -4)
  const sql = 'DELETE  FROM ' + table + ' where ' + _WHERE
 db.query(sql, [], callback)
}

module.exports = {
  insert: insert,
  select: select,
  findOne: findOne,
  del: del,
  update: update
}
